<?php
namespace Home\Controller;

use Think\Controller;

class OauthController extends Controller {
	public function _initialize(){
		/**
		 * TOKEN验证
		 */
		define ( "TOKEN", "mdd88" ); // 将token值设置为你所需要的值，token可由开发者任意填写，用作生成签名。
		define ( 'DEBUG', true );
		// $url_path = dirname(__FILE__);
		$url_path = C ( 'wesetDir' );
		$xml_path = $url_path . "/lib/config/attention.xml";
		if (file_exists ( $xml_path )) {
			$attention_xml = ( array ) simplexml_load_file ( $xml_path );
			$attention = $attention_xml ['attention'];
		} else {
			$attention = "欢迎关注！";
		}
		define ( 'ATTENTION', $attention );
	}
	
	public function index() {
		$this->responseMsg ();
	}
	
	public function valid() {
		$echoStr = $_GET ["echostr"];
		if ($this->checkSignature ()) {
			exit ($echoStr);
		}
	}
	
	public function responseMsg() {
		// get post data, May be due to the different environments
		$postStr = $GLOBALS ["HTTP_RAW_POST_DATA"];
		
		// extract post data
		if (! empty ( $postStr )) {
			// 将XML字串转换成对象
			$postObj = simplexml_load_string ( $postStr, 'SimpleXMLElement', LIBXML_NOCDATA );
			$fromUsername = $postObj->FromUserName;
			$toUsername = $postObj->ToUserName;
			$createTime = $postObj->CreateTime;
			$RX_TYPE = trim ( $postObj->MsgType );
			$userConetnt = trim ( $postObj->Content );
			// $id = $postObj->MsgId;
			
			$time = time ();
			//添加微信用户信息
// 			$fromUsername = trim($fromUsername);
// 			$fromUsername = (string)$fromUsername;
			
//  			$this->addUserAction($fromUsername);
 			
			switch ($RX_TYPE) {
				case "text" :
					$resultStr = $this->handleText ( $postObj );
					break;
				case "image" :
					$resultStr = $this->responseText ( $postObj, "恭喜你，图片上传成功哦!" );
					break;
				case "voice" :
					$resultStr = $this->responseText ( $postObj, "语音发送成功！" );
					break;
				case "video" :
					$resultStr = $this->responseText ( $postObj, "视频上传成功！" );
					break;
				case "link" :
					$resultStr = $this->responseText ( $postObj, "" );
					break;
				case "event" :
					$resultStr = $this->handleEvent ( $postObj );
					break;
				case "location" :
					$resultStr = $this->handleLocation ( $postObj );
					break;
				default :
					$resultStr = "Unknow msg type: " . $RX_TYPE;
					break;
			}
			echo $resultStr;
		} else {
			echo "";
			exit ();
		}
	}
	
	/**
	 * 检验signature
	 * 
	 * @return boolean
	 */
	private function checkSignature() {
		$signature = $_GET ["signature"];
		$timestamp = $_GET ["timestamp"];
		$nonce = $_GET ["nonce"];
		
		$token = TOKEN;
		$tmpArr = array (
				$token,
				$timestamp,
				$nonce 
		);
		sort ( $tmpArr, SORT_STRING );
		$tmpStr = implode ( $tmpArr ); // 将数组转换成一个字串
		$tmpStr = sha1 ( $tmpStr );
		
		if ($tmpStr == $signature) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 关键字回复
	 * 
	 * @param unknown $postObj        	
	 */
	public function handleText($postObj) {
		// 根据关键词回复，判断关键字是图文还是文本消息
		$keyword = trim ( $postObj->Content );
		$openid = $postObj->FromUserName;
		
		$this->sendFail($openid);
		
		
		if (! empty ( $keyword )) {
			// 插入用户发送记录
			if (! empty ( $openid ) && $keyword != '') {
				date_default_timezone_set ( "PRC" );
				$now_time = date ( "Y-m-d H:i:s" );
				$data = array (
						"openid" => "$openid",
						"consult_title_text" => "$keyword",
						"consult_add_time" => "$now_time" 
				);
				M( 'wx_user_consult' )->add( $data );
			}
			
			
			
			//呼叫华胜SA事件
			$sendData = array('OpenID'=>$openid,'Content'=>$keyword);
			$sa = http_post(C('apiWxCallSa'), $sendData);
			
// 			if(stristr ( $keyword, "@sa" ) || stristr ( $keyword, "@SA" ) || stristr ( $keyword, "@Sa" ) || stristr ( $keyword, "@sA" )){
// 				$content = str_replace('@sa', '', (string)$keyword);
// 				$sendData = array('OpenID'=>$openid,'Content'=>$keyword);
// 				$sa = http_post(C('apiWxCallSa'), $sendData);
// 				$sa = json_decode($sa,true);
// 				return $this->responseText ( $postObj, "微信内容已经发送给SA:".$sa );
// 			}
			
			
			// 查询关键词
			$wx_keywords_reply = M ( 'wx_keywords_reply' );
			$where ['keywords_text'] = array (
					'like',
					"%" . $keyword . "%" 
			);
			$one_keyword = $wx_keywords_reply->where ( $where )->order ( 'id desc' )->limit ( 1 )->select ();
			
// 			if (stristr ( strtolower ( $keyword ), "kf" )) {
				// 接入到相应的客服上面去
// 				$keyword = trim ( $keyword );
// 				$wx_kf = M ( 'wx_kf' )->where ( array (
// 						'kf_select_id' => $keyword 
// 				) )->limit ( 1 )->select ();
				
// 				if ($wx_kf) {
// 					$kf_account = $wx_kf [0] ['kf_account'];
// 					return $this->responseOneKfServiceText ( $postObj, $kf_account );
// 				}
// 			} else {
				if (! empty ( $one_keyword[0] )) {
					if ($one_keyword[0]['reply_type'] == 1) {
						// 图文信息
						$news_arr = M ( 'wx_news_image' )->where ( array (
								'news_key' => $one_keyword[0]['reply_detail'] 
						) )->limit ( 0, 8 )->select ();
						
						return $this->transmitNews ( $postObj, $news_arr );
					} else {
						// 文本信息
						return $this->responseText ( $postObj, $one_keyword[0]['reply_detail'] );
					}
				} 
// 				else {
// 					return $this->responseText ( $postObj, "微信客服为您提供方便快捷的7*24小时全天候服务，包括自助服务及人工服务。如果想要人工服务请输入@sa+内容或者@SA+内容。" );
					
// 				}
// 			}
		} else {
			return $this->responseText ( $postObj, ATTENTION );
		}
	}
	
	/**
	 * 回复文本消息
	 * 
	 * @param unknown $object        	
	 * @param unknown $content
	 *        	消息内容
	 * @param number $flag        	
	 * @return string
	 */
	public function responseText($object, $content, $flag = 0) {
		$textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>%d</FuncFlag>
                    </xml>";
		$resultStr = sprintf ( $textTpl, $object->FromUserName, $object->ToUserName, time (), $content, $flag );
		return $resultStr;
	}
	
	/**
	 * 将消息发送到所有客服
	 * 
	 * @param unknown $object        	
	 * @param unknown $content
	 *        	消息内容
	 * @param number $flag        	
	 * @return string
	 */
	public function responseServiceText($object, $content, $flag = 0) {
		$textTpl = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[transfer_customer_service]]></MsgType>
					</xml>";
		$resultStr = sprintf ( $textTpl, $object->FromUserName, $object->ToUserName, time (), $flag );
		return $resultStr;
	}
	
	/**
	 * 将消息发送到特定客服
	 * 
	 * @param unknown $object        	
	 * @param unknown $content
	 *        	消息内容
	 * @param number $flag        	
	 * @return string
	 */
	public function responseOneKfServiceText($object, $kf_account, $flag = 0) {
		$textTpl = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName>
						<CreateTime>%s</CreateTime><MsgType><![CDATA[transfer_customer_service]]></MsgType>
						<TransInfo><KfAccount><![CDATA[%s]]></KfAccount></TransInfo></xml>";
		$resultStr = sprintf ( $textTpl, $object->FromUserName, $object->ToUserName, time (), $kf_account, $flag );
		return $resultStr;
	}
	
	/**
	 * 回复图文消息
	 * 图文回复如果不加连接就不会显示“查看全文”
	 */
	private function transmitNews($object, $newsArray) {
		if (! is_array ( $newsArray )) {
			return;
		}
		$itemTpl = "<item>
		        <Title><![CDATA[%s]]></Title>
		        <Description><![CDATA[%s]]></Description>
		        <PicUrl><![CDATA[%s]]></PicUrl>
		        <Url><![CDATA[%s]]></Url>
		    </item>
		";
		$item_str = "";
		foreach ( $newsArray as $item ) {
			if (empty ( $item ['news_href'] )) {
// 				$file_path = dirname ( 'http://' . $_SERVER ['SERVER_NAME'] . $_SERVER ['PHP_SELF'] );
				$file_path = dirname ( 'http://' . $this->_server('HTTP_HOST') . $_SERVER ['PHP_SELF'] );
				$href = $file_path . "/Public/admin/news/news_wx_id" . $item ['id'] . ".html";
			} else {
				$href = $item ['news_href'];
			}
			$item_str .= sprintf ( $itemTpl, $item ['news_title'], $item ['news_zhaiyao'], $item ['news_img_path'], $href );
		}
		$xmlTpl = "<xml>
    	<ToUserName><![CDATA[%s]]></ToUserName>
    	<FromUserName><![CDATA[%s]]></FromUserName>
    	<CreateTime>%s</CreateTime>
    	<MsgType><![CDATA[news]]></MsgType>
    	<ArticleCount>%s</ArticleCount>
    	<Articles>
    	$item_str</Articles>
    	</xml>";
		
		$result = sprintf ( $xmlTpl, $object->FromUserName, $object->ToUserName, time (), count ( $newsArray ) );
		return $result;
	}
	
	/**
	 * 事件处理
	 * 
	 * @param unknown $object        	
	 * @return string
	 */
	public function handleEvent($object) { // 菜单判断
	                                       // 取出关注要回复的
	                                       
		// Event是事件类型(subscribe,LOCATION)
		$oneEvent = $object->Event;
		// EventKey是菜单事件的key值
		$key = $object->EventKey;
		
		
		
		// 关注事件
		if ($oneEvent == "subscribe" || $oneEvent == "SUBSCRIBE") {
		
			
			if (! empty ( $object->Ticket )) {
				
				// 关注事件
				$SceneID = str_replace('qrscene_', '', (string)$key);
				$openid = (string)$object->FromUserName;
				
				try {
					
					date_default_timezone_set("PRC");
					$times= date("Y-m-d H:i:s");
					$data = array('openid'=>$openid,'sceneId'=>$SceneID,'times'=>$times,'types'=>'subscribe');
					M('wx_scan_record')->add($data);
					
					$url = C('apiWxSubscribe')."SceneID=".$SceneID."&OpenID=".$openid;
					$sendRes = httpGet($url);
					$sendRes = json_decode($sendRes,true);
					
				} catch (Exception $e) {
				}
				
				
					
				$resultStr = $this->responseText ( $object, ATTENTION);
				return $resultStr;
				
				// 扫码事件
// 				if (! stristr ( $key, "qrscene_" )) {
// 					$key = "qrscene_" . $key;
// 				}
// 				$tuwenkey = array ();
// 				if (stristr ( $tuwenkey, "key_" )) {
// 					// 这个图文事件
// 					$news_arr = M ( 'wx_news_image' )->where ( array (
// 							'news_key' => $tuwenkey 
// 					) )->limit ( 0, 8 )->select ();
// 					$resultStr = $this->transmitNews ( $object, $news_arr );
// 					return $resultStr;
// 				} else {
// 					// 文本消息
// 					// 查询关键词
// 					$wx_keywords_reply = M ( 'wx_keywords_reply' );
// 					$where ['keywords_text'] = array (
// 							'like',
// 							"%" . $tuwenkey . "%" 
// 					);
// 					$one_keyword = $wx_keywords_reply->where ( $where )->order ( 'id desc' )->limit ( 1 )->select ();
// 					$resultStr = $this->responseText ( $object, $one_keyword[0]['reply_detail'] );
// 					return $resultStr;
// 				}
				
				
				
			} else {
				// 关注事件
				$SceneID = str_replace('qrscene_', '', (string)$key);
				$openid = (string)$object->FromUserName;
				
				try {
					
					date_default_timezone_set("PRC");
					$times= date("Y-m-d H:i:s");
					$data = array('openid'=>$openid,'sceneId'=>$SceneID,'times'=>$times,'types'=>'subscribe');
					M('wx_scan_record')->add($data);
						
					$url = C('apiWxSubscribe')."SceneID=".$SceneID."&OpenID=".$openid;
					$sendRes = httpGet($url);
					$sendRes = json_decode($sendRes,true);
						
				} catch (Exception $e) {
				}
				
				$resultStr = $this->responseText ( $object, ATTENTION );
				return $resultStr;
			}
		}else if ($oneEvent == "SCAN" || $oneEvent == "scan") {
			
			//扫码事件
			$SceneID = (string)$key;
			
			$openid = (string)$object->FromUserName;
			try {
				
				date_default_timezone_set("PRC");
				$times= date("Y-m-d H:i:s");
				$data = array('openid'=>$openid,'sceneId'=>$SceneID,'times'=>$times,'types'=>'scan');
				M('wx_scan_record')->add($data);
				
				$url = C('apiWxSubscribe')."SceneID=".$key."&OpenID=".$openid;
				$sendRes = httpGet($url);
				$sendRes2 = $sendRes;
				$sendRes = json_decode($sendRes,true);
			} catch (Exception $e) {
			}
			
// 			if($SceneID >= 1000000000 && $SceneID <= 2000000000){
// 				$jumpUrl = 'http://'.$this->_server('HTTP_HOST').U('Card/bind');
// 				$str = "您好，您已经成功将微信号绑定华胜会员。\n我们将为您送上100元现金券，到店\n凭券可抵扣现金,<a href='".$jumpUrl."'>点击这里</a>即可进入领取。\n如有疑问，请咨询400-8033-707";
// 				$resultStr = $this->responseText ( $object, $str);
// 				return $resultStr;
// 			}else{
// 				$resultStr = $this->responseText ( $object, ATTENTION);
// 				return $resultStr;
// 			}

			
			$resultStr = $this->responseText ( $object, ATTENTION);
			return $resultStr;
			
			
		}else if ($oneEvent == "CLICK" || $oneEvent == "click") {
			
			if (! empty ( $key )) {
				
				
				
				if($key == "key_phone"){
					$this->sendFail($object->FromUserName);
					$customer_info = "华胜连锁服务热线：400-8033-707";
					$resultStr = $this->responseText ( $object, $customer_info );
					return $resultStr;
				}
				
				/*
				 * 思路：判断点击的菜单推送出的信息类型，如果以“key_”开头，则为图文消息 反之为：文本消息 判断是否是客服的key值：custom_service
				 */
				if ($key == "custom_service") {
					// 客服，调用接口获取说有客服信息
					$customer_info = "欢迎使用华胜客服，请选择相应服务：\n";
					
					$kf_arr = M ( 'wx_kf' )->select ();
					foreach ( $kf_arr as $kf_key => $kf_val ) {
						$customer_info .= "[kf" . $kf_val ['kf_id'] . "] " . $kf_val ['kf_nick'] . "\n";
					}
					$customer_info .= "回复字母“kf”+后面的数字如：kf1001，我们为您接入相应客服。";
					$resultStr = $this->responseText ( $object, $customer_info );
					return $resultStr;
				}
				if (stristr ( $key, "key_" )) {
					// 这个图文事件
					$m = M ( 'wx_news_image' );
					$where = array('news_key'=>"$key");
					$news_arr = $m->where($where)->limit(8)->select ();
					
					$resultStr = $this->transmitNews ( $object, $news_arr );
					return $resultStr;
				} else {
					// 文本消息
					$wx_keywords_reply = M ( 'wx_keywords_reply' );
					$where ['keywords_text'] = array (
							'like',
							"%" . $key . "%" 
					);
					$one_keyword = $wx_keywords_reply->where ( $where )->order ( 'id desc' )->limit ( 1 )->select ();
					$resultStr = $this->responseText ( $object, $one_keyword [0] ['reply_detail'] );
					return $resultStr;
				}
			} else {
				
				
				
				$resultStr = $this->responseText ( $object, ATTENTION );
				return $resultStr;
			}
		}else if($oneEvent == 'TEMPLATESENDJOBFINISH' || $oneEvent == "templatesendjobfinish"){
			//模板消息添加记录
			$fromUsername = $object->FromUserName;
			$toUsername = $object->ToUserName;
			$createTime = $object->CreateTime;
			$msgType = trim ( $object->MsgType );
			$event = trim ( $object->Event );
			$msgID = trim ( $object->MsgID );
			$status = trim ( $object->Status );
			
				
			$data = array("toUserName"=>"$toUsername","fromUserName"=>"$fromUsername","createTime"=>"$createTime","msgType"=>$msgType,"event"=>$event,"msgID"=>$msgID,"status"=>$status);
				
			$addFlage = M('wx_module_message')->add($data);
			
		}else if($oneEvent == 'CARD_PASS_CHECK' || $oneEvent == 'card_pass_check'){
			//卡券通过审核
			$fromUsername = (string)$object->FromUserName;
			$toUsername = (string)$object->ToUserName;
			$createTime = $object->CreateTime;
			
			$checkTimes = time();
			$event = $oneEvent;
			$cardid = $object->cardId;
			//卡券title、及有效期的开始时间、结束时间
			$arr = $this->queryDetailByCardId($cardid);
			$cardTitle = $arr['cardTitle'];
			
			
			
			$data = array("toUserName"=>"$toUsername","fromUserName"=>"$fromUsername","createTime"=>"$createTime",
					"checkTimes"=>$checkTimes,"event"=>$event,"cardId"=>$cardid,"cardTitle"=>$cardTitle);
			
			
			M('wx_card_check')->add($data);
			
			
			
			
		}else if($oneEvent == 'CARD_NOT_PASS_CHECK' || $oneEvent == 'card_not_pass_check'){
			//卡券不通过审核
			$fromUsername = (string)$object->FromUserName;
			$toUsername = (string)$object->ToUserName;
			$createTime = (string)$object->CreateTime;
			$checkTimes = time();
			$event = $oneEvent;
			$cardid = (string)$object->CardId;
			//卡券title、及有效期的开始时间、结束时间
			$arr = $this->queryDetailByCardId($cardid);
			$cardTitle = $arr['cardTitle'];
			
			$data = array("toUserName"=>"$toUsername","fromUserName"=>"$fromUsername","createTime"=>"$createTime",
					"checkTimes"=>$checkTimes,"event"=>$event,"cardId"=>$cardid,"cardTitle"=>$cardTitle);

			M('wx_card_check')->add($data);
			
			
		}else if($oneEvent == 'USER_GET_CARD' || $oneEvent == 'user_get_card'){
			
			//领取卡券事件推送
			$fromUsername = (string)$object->FromUserName;//领取方帐号
			$toUsername = (string)$object->ToUserName;//开发者微信号
			$friendUserName = (string)$object->FriendUserName;//赠送方帐号IsGiveByFriend为1时填写该参数
			
			$createTime = (string)$object->CreateTime;
			$drawTimes = time();
			$cardid = (string)$object->CardId;//卡券 ID
			$isGiveByFriend = (string)$object->IsGiveByFriend;//是否为转赠，1 代表是，0 代表否。
			$outerId =  (int)$object->OuterId;//领取场景值，用于领取渠道数据统计。可在生成二维码接口及添加JS API接口中自定义 该字段的整型值
			$userCardCode = (string)$object->UserCardCode;//自定义CODE
			
			//卡券title、及有效期的开始时间、结束时间
			$arr = $this->queryDetailByCardId($cardid);
			
			$cardTitle = $arr['cardTitle'];
			$begin_times = $arr['begin_times'];
			$end_times = $arr['end_times'];
			$color = $arr['color'];
			$reduce_cost = $arr['reduce_cost'];
			
			//获取客户客户编号
			$clientCode = $this->getClientCode($fromUsername);
			
			
			$data = array("toUserName"=>"$toUsername","fromUserName"=>"$fromUsername","friendUserName"=>$friendUserName,"createTime"=>"$createTime","drawTimes"=>$drawTimes,"cardId"=>$cardid,
			"isGiveByFriend"=>$isGiveByFriend,"outerId"=>$outerId,"userCardCode"=>$userCardCode,
			"cardTitle"=>$cardTitle,"begin_times"=>$begin_times,"end_times"=>$end_times,"cardColor"=>$color,
					"reduceCost"=>$reduce_cost,"clientCode"=>$clientCode);
			M('wx_card_draw')->add($data);
			
			
			
			//如果是朋友赠送的，把朋友赠送的设为已经使用
			$data_give = array("fromUserName"=>$friendUserName,"userCardCode"=>$userCardCode,"cardId"=>$cardid);
			M('wx_card_draw')->where($data_give)->save(array("isUse"=>2));
			
			
			$resultStr = $this->responseText ( $object, '卡券领取成功,请到微信卡包里查看！');
			return $resultStr;
			
		}else if($oneEvent == 'USER_DEL_CARD' || $oneEvent == 'user_del_card'){
			
			//删除卡券事件推送
			$fromUsername = (string)$object->FromUserName;//领取方帐号
			$toUsername = (string)$object->ToUserName;//开发者微信号
			$deleteTimes = time();
			$createTime = (string)$object->CreateTime;
			$cardid = (string)$object->CardId;//卡券 ID
			$userCardCode = (string)$object->UserCardCode;//自定义CODE
			
			//卡券title、及有效期的开始时间、结束时间
			$arr = $this->queryDetailByCardId($cardid);
			$cardTitle = $arr['cardTitle'];
			
			
			
			
			$data = array("toUserName"=>"$toUsername","fromUserName"=>"$fromUsername","createTime"=>"$createTime","deleteTimes"=>$deleteTimes,"cardId"=>$cardid,"userCardCode"=>$userCardCode,
			"cardTitle"=>$cardTitle);
				
			M('wx_card_delete')->add($data);
			
			$resultStr = $this->responseText ( $object, '卡券删除成功！');
			return $resultStr;
			
		}else if($oneEvent == 'USER_CONSUME_CARD' || $oneEvent == 'user_consume_card'){
			//核销卡券事件推送
			$fromUsername = (string)$object->FromUserName;//发送方帐号
			$toUsername = (string)$object->ToUserName;//开发者微信号 
			$cancelTimes = time();
			$createTime = (string)$object->CreateTime;
			$cardid = (string)$object->CardId;//卡券 ID
			$userCardCode = (string)$object->UserCardCode;//自定义CODE
			
			
			//卡券title、及有效期的开始时间、结束时间
			$arr = $this->queryDetailByCardId($cardid);
			$cardTitle = $arr['cardTitle'];
			$begin_times = $arr['begin_times'];
			$end_times = $arr['end_times'];
			$color = $arr['color'];
			$reduce_cost = $arr['reduce_cost'];
			
			//获取客户客户编号
			$clientCode = $this->getClientCode($fromUsername);
			
			
			//添加卡券核销记录
			$data = array("toUserName"=>"$toUsername","fromUserName"=>"$fromUsername","createTime"=>"$createTime",
					"cancelTimes"=>$cancelTimes,"cardId"=>$cardid,"userCardCode"=>$userCardCode,
					"cardTitle"=>$cardTitle,"begin_times"=>$begin_times,"end_times"=>$end_times,"cardColor"=>$color,
					"reduceCost"=>$reduce_cost,"clientCode"=>$clientCode);
			M('wx_card_cancel')->add($data);
			
			//更新卡券为已使用
			$dataUse = array("fromUserName"=>"$fromUsername","userCardCode"=>$userCardCode,"cardId"=>$cardid);
			M('wx_card_draw')->where($dataUse)->save(array("isUse"=>2));
			
			//查询是不是朋友送的卡券
			$arr = array('userCardCode'=>$userCardCode,"cardId"=>$cardid,"fromUserName"=>"$fromUsername","isSendModulMessage"=>1);
			$cardDraw = M('wx_card_draw')->where($arr)->find();
			$friendUserName = $cardDraw['friendUserName'];
			$cid = $cardDraw['id'];
			
			if (!empty($friendUserName)) {
				
				$where = array('id'=>$cid);
				$data = array('isSendModulMessage'=>2);
				M('wx_card_draw')->where($where)->save($data);
				//是朋友送的推送模板消息
// 				$this->sendModulMessage($friendUserName);
// 				$resultStr = $this->responseText ( $object, '是朋友送的核销卡券成功！friendUserName:'.$friendUserName);
// 				return $resultStr;
			}else{
// 				$resultStr = $this->responseText ( $object, '不是朋友送的核销卡券成功！friendUserName:'.$friendUserName);
// 				return $resultStr;
			}
			
			$resultStr = $this->responseText ($object,'核销卡券成功！');
			return $resultStr;
			
		}
		
		
	}
	
	
	
	/**
	 * 根据cardid返回卡券title、及有效期的开始时间、结束时间
	 * @param unknown $cardid
	 * @return multitype:unknown string
	 */
	private function queryDetailByCardId($cardid){
		
		$arr = $this->queryDetail($cardid);
		$card_type = strtolower($arr['card']['card_type']);
		$cardTitle = $arr['card'][$card_type]['base_info']['title'];
		$date_info_type = $arr['card'][$card_type]['base_info']['date_info']['type'];
		$color = $arr['card'][$card_type]['base_info']['color'];
		$reduce_cost = 1;
		if($card_type == 'cash'){
			$reduce_cost = $arr['card'][$card_type]['reduce_cost'];
			$reduce_cost = intval($reduce_cost/100);
		}
		//date_info_type使用时间的类型，仅支持选择一种时间类型的字段填入。DATE_TYPE_FIX_TIME_RANGE 1：固定日期区间，DATE_TYPE_FIX_TERM 2：固定时长（自领取后按天算）
		if($date_info_type == 1 || $date_info_type == 'DATE_TYPE_FIX_TIME_RANGE'){
			$begin_times = $arr['card'][$card_type]['base_info']['date_info']['begin_timestamp'];
			$end_times = $arr['card'][$card_type]['base_info']['date_info']['end_timestamp'];
		}else if($date_info_type == 2 || $date_info_type == 'DATE_TYPE_FIX_TERM'){
			$fixed_term = $arr['card'][$card_type]['base_info']['date_info']['fixed_term'];
			$fixed_begin_term = $arr['card'][$card_type]['base_info']['date_info']['fixed_begin_term'];
			$fixed_term = $fixed_term -1 + $fixed_begin_term;
			$begin_times = date("Y-m-d",strtotime("+".$fixed_begin_term." day"));
			$begin_times = strtotime($begin_times);
			$end_times = date("Y-m-d",strtotime("+".$fixed_term." day"));
			$end_times = strtotime($end_times);
		}
		
		return array('cardTitle'=>$cardTitle,"begin_times"=>$begin_times,"end_times"=>$end_times,"color"=>$color,"reduce_cost"=>$reduce_cost);
	}
	
	/**
	 * 根据openid获取客户编号,先查询数据库是否有相关的记录，如果没有就调用接口查询
	 * @param unknown $fromUsername
	 * @return unknown
	 */
	private function getClientCode($fromUsername){
		$clientCode = '';
		
		$urlBind = C('apiIsBinding');
		$urlBind = $urlBind.$fromUsername;
		$resultBindArr = httpGet($urlBind);
		$resultBindArr = json_decode($resultBindArr,true);
		if ($resultBindArr['resultCode'] == 200) {
			$clientCode = $resultBindArr['result']['ClientCode'];
		}
		
		return $clientCode;
	}
	
	/**
	 * 查询卡券详细信息
	 * @param unknown $card_id
	 * @return mixed
	 */
	private function queryDetail($card_id){
		$access_token = getAccessToken();
		$url = "https://api.weixin.qq.com/card/get?access_token=".$access_token;
	
		$json = array('card_id'=>$card_id);
		 
		$json = json_encode($json);
		 
		$res = https_post_json($url, $json);
		 
		$res = json_decode($res[1],true);
		 
		return $res;
	}
	
	
	/**
	 * 推送模板消息
	 */
	private function sendModulMessage($toUser){
		date_default_timezone_set('PRC');
		$times =  date('Y-m-d H:i:s');
		$template = array(
				'touser' => $toUser,
				'template_id' => '2x79iZoSNh00JXvRX1Die0-DTuYVzNU5x-3AmS2Gv8A',
				'url' => 'http://www.joyweixin.com/clients/harson_wechat/index.php/ModuleMessage/responseMsg',
				'topcolor'=>'#c0c0c0',
				'data' => array (
						'first' => array('value'=>'test','color'=>'#173177'),
						'dealername' => array('value'=>'华胜','color'=>'#173177'),
						'svrdate' => array('value'=>$times,'color'=>'#173177'),
						'svrproject' => array('value'=>'汽车检测','color'=>'#173177'),
						'remark' => array('value'=>'remark!','color'=>'#173177')
				)
		);
		$access_token = getAccessToken();
		$url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$access_token;
		$ch = curl_init();
		//设置超时
		curl_setopt($ch, CURLOPT_TIMEOUT, 60);
		curl_setopt($ch,CURLOPT_URL, $url);
		if(defined('CURLOPT_IPRESOLVE') && defined('CURL_IPRESOLVE_V4')) {
			curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
		}
		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
		curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
		//设置header
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		//要求结果为字符串且输出到屏幕上
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		//post提交方式
		curl_setopt($ch, CURLOPT_POST, TRUE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, urldecode(json_encode($template)));
		//运行curl，结果以json形式返回
		$res = curl_exec($ch);
		curl_close($ch);
		echo $res;
	}
}